package com.genius.utils;

import com.genius.Interceptor.HeaderInterceptor;
import com.genius.core.LoginUser;
import com.genius.enums.ResponseType;
import com.genius.exception.GraceException;
import com.genius.exception.IotException;
import com.genius.system.pojo.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 安全工具类
 */
public class SecurityUtils {

    /**
     * 用户ID
     **/
    public static Long getUserId() {
        try {
            return getLoginUser().getUser().getUserId();
        } catch (Exception e) {
            throw new IotException(ResponseType.UN_LOGIN);
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUser().getUsername();
        } catch (Exception e) {
            throw new IotException(ResponseType.UN_LOGIN);
        }
    }

    /**
     * 获取用户信息
     **/
    public static User getUser() {
        try {
            return getLoginUser().getUser();
        } catch (Exception e) {
            throw new IotException(ResponseType.UN_LOGIN);
        }
    }

    /**
     *获取登陆用户信息
     * @return 登陆用户信息
     */
    public static LoginUser getLoginUser(){
        LoginUser loginUser = HeaderInterceptor.currentUser.get();
        if(loginUser == null){
            GraceException.display(ResponseType.UN_LOGIN);
        }
        return loginUser;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

}